package org.openharmony.qttool;

import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBScrollPane;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;

public class QtSDKSettingsConfigurable implements Configurable {
    private JPanel mainPanel;

    private QtSDKTable table;
    private boolean isModified;
    public QtSDKSettingsConfigurable() {
        isModified = false;
    }

    @Override
    public String getDisplayName() {
        return "Qt SDK";
    }
    @Nullable
    @Override
    public JComponent createComponent() {
        if (mainPanel == null) {
            BorderLayout layout = new BorderLayout();
            mainPanel = new JPanel(layout);

            table = new QtSDKTable();
            JBScrollPane scrollPane = new JBScrollPane(table);
            mainPanel.add(scrollPane, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
            JButton addButton = new JButton("Add");
            JButton deleteButton = new JButton("Delete");

            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String selectedQt = getQmake();
                    if (selectedQt == null)
                        return;
                    if (!table.addSDK(selectedQt)) {
                        Messages.showErrorDialog(table.errorString(), "Error");
                        return;
                    }
                    isModified = true;
                    notifyConfigurableUpdate();
                }
            });

            deleteButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int selectedRow = table.getSelectedRow();
                    if (selectedRow != -1) {
                        table.removeSDK(selectedRow);
                        isModified = true;
                        notifyConfigurableUpdate();
                    }
                }
            });
            buttonPanel.add(addButton);
            buttonPanel.add(deleteButton);
            mainPanel.add(buttonPanel, BorderLayout.EAST);
        }
        return mainPanel;
    }

    private static final class QmakeFileChooserDescriptor extends FileChooserDescriptor{
        private QmakeFileChooserDescriptor() {
            super(true, false, false, false, false, false);
            setTitle("Select Qmake");
        }
        @Override
        public boolean isFileSelectable(@Nullable VirtualFile file) {
            if (file == null) {
                return false;
            }
            return file.getName().equals("qmake.exe") || file.getName().equals("qmake") || file.isDirectory();
        }
        @Override
        public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            boolean result = super.isFileVisible(file, showHiddenFiles);
            return isFileSelectable(file) && result;
        }
    }

    private static String getQmake() {
        VirtualFile file = FileChooser.chooseFile(new QmakeFileChooserDescriptor(), null, null);
        if (file != null) {
            File f = VfsUtilCore.virtualToIoFile(file);
            return f.toString();
        }
        return null;
    }

    @Override
    public boolean isModified() {
        // Check if your settings have been modified
        return isModified;
    }

    @Override
    public void apply() throws ConfigurationException {
        // Apply your settings here
        // This method is called when the user clicks "OK" in the Settings dialog
        if (!isModified)
            return;
        QtSDKTableModel model = (QtSDKTableModel) table.getModel();
        if (model == null)
            return;
        ArrayList<QtSDK> all = model.allKits();
        for (QtSDK sdk : all) {
            if (!QtSDKManager.getInstance().contains(sdk)) {
                QtSDKManager.getInstance().add(sdk);
            }
        }
        ArrayList<QtSDK> removed = model.removedKits();
        for (QtSDK sdk : removed) {
            QtSDKManager.getInstance().remove(sdk);
        }
        QtSDKManager.save();
        isModified = false;
    }

    @Override
    public void reset() {
        // Reset your settings to the initial state
        // This method is called when the user clicks "Cancel" in the Settings dialog
        table.setModel(new QtSDKTableModel());
        table.resizeColumnWidth();
        isModified = false;
    }

    @Override
    public void disposeUIResources() {
        // Dispose any resources when the UI is no longer needed
        mainPanel = null;
    }

    private void notifyConfigurableUpdate() {
        // \src\com\intellij\openapi\options\newEditor\ConfigurableEditor.java
        // only mouse key event can update reset and apply button state
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        KeyEvent keyEvent = new KeyEvent(table, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_A, 'A');
        toolkit.getSystemEventQueue().postEvent(keyEvent);
    }
}

